var express = require('express');
var router = express.Router();
var fs = require("fs");
var Db = require("../database");
var config = require("../config");
var logger = require("../logger");

function onlogin(req, res){
    var username = req.body.username;
    var password = req.body.password;
    var sessionId = req.cookies[config.sessionName];

    if(!username || !password){
        logger.info(username)
        return res.json({status:0,error:config.ErrorStr.missParamErr});
    }
    Db.getConnection(function(err, conn){
        if(err){
            res.json({status:0,error:err.message});
        }else{
            conn.collection(Db.sessionCollection).findOne({id:sessionId},function(err,sessionInfo){
                if(err){
                    res.json({status:0,error:err.message});
                }else{
                    Db.removeExpiredSession(function () {
                        conn.collection(Db.adminCollection).findOne({username:username},function(err, adminInfo){
                            if(err){
                                res.json({status:0,error:err.message});
                            }else{
                                var isLogin = adminInfo && adminInfo.password == password;
                                logger.info(adminInfo);
                                if(adminInfo){
                                    if(adminInfo.password != password){
                                        res.json({status:0,error:config.ErrorStr.passwordErr});
                                    }else{
                                        Db.createSession(adminInfo,function (err,sessionId) {
                                            res.cookie(config.sessionName,sessionId,{expires: new Date(Date.now() + config.sessionTimeout),maxAge: config.sessionTimeout, httpOnly: false});
                                            res.json({status: 1, error: '',data:{isLogin:isLogin,right:adminInfo.right}});
                                        });
                                    }
                                }else{
                                    res.json({status: 0, error: config.ErrorStr.accountNotExistsErr});
                                }
                            }
                        })
                    })
                }
            });
        }
    })
}

function regist(req,res){
    var username = req.body.username;
    var password = req.body.password;
    if(!username || !password){
        res.json({status:0,error:config.ErrorStr.missParamErr});
    }else{
        Db.getConnection(function(err,conn){
            if(err){
                res.json({status:0,error:err.message});
            }else{
                conn.collection(Db.adminCollection).find({username:username},{fields:{_id:1},limit:1}).toArray(function(err,info){
                    if(err){
                        res.json({status:0,error:err.message});
                    }else{
                        if(info){
                            if(info.length < 1){
                                var newRegist = {username:username,password:password,right:0,gid:0,date:new Date()};
                                conn.collection(Db.adminCollection).insert(newRegist,function(err,result){
                                    if(err){
                                        res.json({status:0,error:err.message});
                                    }else{
                                        res.json({status:1,error:"",data:result});
                                    }
                                })
                            }else{
                                res.json({status:0,error:config.ErrorStr.accountExistsErr});
                            }
                        }else{
                            res.json({status:0,error:config.ErrorStr.reqErr});
                        }
                    }
                })
            }
        })
    }
}

function logout(req,res){
    var sessionId = req.cookies[config.sessionName];
    Db.getConnection(function(err,conn){
        if(err){
            res.json({status:0,error:err.message});
        }else{
            conn.collection(Db.sessionCollection).find({id:sessionId},function(err,info){
                if(err){
                    res.json({status:0,error:err.message});
                }else{
                    if(info){
                        conn.collection(Db.sessionCollection).remove({id:sessionId},function(err){
                            if(err){
                                res.json({status:0,error:err.message});
                            }else{
                                res.clearCookie(config.sessionName);
                                res.json({status: 1, error:''});
                            }
                        })
                    }else{
                        res.json({status: 1, error:''});
                    }
                }
            });
        }
    })
}

router.post('/onlogin', onlogin);
router.post('/regist', regist);
router.post('/logout', logout);

module.exports = router;
